package com.banmao.CarlCamp.Day07;

import java.util.ArrayList;
import java.util.Iterator;

public class Offer05 {

    public String replaceSpace(String s) {
        ArrayList<Integer> whiteSpace = new ArrayList<>();
        char[] chars = s.toCharArray();

        for (int i = 0; i < chars.length; i++) {
            if (Character.isWhitespace(chars[i])) {
                whiteSpace.add(i);
            }
        }

        if (whiteSpace.size() == 0) {
            return s;
        }

        int whiteSpaceNum = whiteSpace.size();
        char[] newChars = new char[chars.length + whiteSpaceNum * 2];
        Iterator<Integer> iterator = whiteSpace.iterator();

        Integer next = iterator.next();
        for (int i = 0, j = 0; i < newChars.length; i++, j++) {
            if (next == j) {
                newChars[i] = '%';
                newChars[++i] = '2';
                newChars[++i] = '0';
                if (iterator.hasNext()) {
                    next = iterator.next();
                }
            } else {
                newChars[i] = chars[j];
            }
        }

        return String.valueOf(newChars);
    }

    public static void main(String[] args) {
        Offer05 offer05 = new Offer05();
        String s = offer05.replaceSpace("Hello World lisi !");
        System.out.println(s);
    }

}
